package com.base.base

import android.app.Activity
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.annotation.FloatRange
import com.base.R

/**
 * 提示窗口基类
 */
abstract class IDialog(private val activity : Activity): PopupWindow(){

    private var gravity = Gravity.CENTER
    private var enableAnim = true
    private var alpha = 0.5f
    protected abstract val layoutRes: Int // 布局资源ID

    init {
        width = ViewGroup.LayoutParams.WRAP_CONTENT
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        setEnableAnim(enableAnim)
        isFocusable = true
        contentView = LayoutInflater.from(activity).inflate(layoutRes,null)
        initLayout()
    }

    /**
     * 初始化布局
     */
    open fun initLayout(){}

    /**
     * 绑定数据
     */
    open fun bindData(){}


    /**
     * 设置是否启用动画 默认启用
     *  如果启用动画 则根据窗口显示位置决定使用哪种动画
     */
    fun  setEnableAnim(enableAnim: Boolean){
        this.enableAnim = enableAnim
        animationStyle = if (enableAnim) {if(gravity == Gravity.BOTTOM) R.style.DialogAnimation_Bottom else R.style.DialogAnimation_Center} else -1
    }

    /**
     * 设置窗口显示位置 默认居中
     */
    fun setGravity(gravity: Int){
        this.gravity = gravity
        setEnableAnim(enableAnim)
    }

    /**
     * 设置窗口透明度
     */
    fun setAlpha(@FloatRange(from = 0.0,to = 1.0) alpha: Float){
        if(this.alpha != alpha){
            this.alpha = alpha
            if(isShowing){ windowAlpha(alpha) }
        }
    }

    /**
     * 显示对话框时设置窗口透明度
     */
    override fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int) {
        windowAlpha(alpha)
        super.showAtLocation(parent, gravity, x, y)
    }

    /**
     * 关闭窗对话框时让窗口不再透明
     */
    override fun dismiss() {
        if (isShowing){
            super.dismiss()
            windowAlpha(1.0f)
        }
    }

    /**
     * 获取加载的窗口
     */
    fun getActivity(): Activity{
        return activity
    }

    /**
     * 显示窗口 每次显示窗口前调用绑定数据接口 实现数据刷新的动作
     */
    open fun  show(): IDialog{
        bindData()
        if(!isShowing) showAtLocation(activity.window.decorView,gravity,0,0)
        return this
    }

    /**
     * 调整窗口透明度
     */
    private fun windowAlpha(@FloatRange(from = 0.0, to = 1.0) alpha: Float) {
        val params = activity.window.attributes
        params.alpha = alpha
        activity.window.attributes = params
    }


    /**
     * 会话监听回调
     */
    interface Listener<A>{
        fun complete(a: A? = null){}
    }

}